package com.example.zjhuojback.mapper;

import com.example.zjhuojback.entity.Forum;
import com.example.zjhuojback.entity.User;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface UserMapper {

    @Insert("insert into `user` (username, password, name, signature, email, avatar, permission) " +
            "values (#{username}, #{password}, #{name}, #{signature}, #{email}, #{avatar}, #{permission})")
    void insert(User user);

    @Update("update `user` set password = #{password}, name = #{name}, signature = #{signature}, " +
    "email = #{email}, avatar = #{avatar} where username = #{username}")
    void updateUser(User user);

    @Delete("delete from `user` where id = #{id}")
    void deleteUser(Integer id);

    @Update("update `user` set password = 888888 where id = #{id}")
    void resetPossword(Integer id);

    @Select("select * from `user` ORDER BY id ASC")
    List<User> selectAll();

    @Select("select * from `user` where username = #{username}")
    User selectByUsername(String username);

    @Select("select * from `user` where id = #{id}")
    User selectById(@Param("id") Integer id);

    @Update("UPDATE `user` SET lastLoginTime = #{loginTime}, lastLoginIp = #{ip} WHERE id = #{id}")
    void updateLoginTimeAndIp(@Param("id") Integer id,
                              @Param("loginTime") LocalDateTime loginTime,
                              @Param("ip") String ip);

    // 提交数+1
    @Update("UPDATE `user` SET submissions = submissions + 1 WHERE username = #{username}")
    void updateSubmit(@Param("username") String username);
    // AC数+1
    @Update("UPDATE `user` SET submissions = submissions + 1, solved = solved + 1 WHERE username = #{username}")
    void updateAccept(@Param("username") String username);

    // 根据id获得用户信息
    @Select({
            "<script>",
            "SELECT id, name, username FROM `user` WHERE id IN",
            "<foreach item='id' index='index' collection='userIds' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "ORDER BY id ASC",
            "</script>"
    })
    List<User> getUsersByIds(@Param("userIds") List<Integer> userIds);

    @Update("UPDATE `user` SET permission = #{permission} WHERE permission != 1")
    void updateUserPermissionAll(@Param("permission") Integer permission);

    @Update("UPDATE `user` SET permission = #{permission} WHERE username = #{username}")
    void updateUserPermission(@Param("username") String username,
                              @Param("permission") Integer permission);
}
